//
//  BRTools.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/8/30.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRTools.h"
#import "BROrederListViewController.h"
#import "BRPaymentViewController.h"
#import "BROrderDetailModel.h"

#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>

@implementation BRTools


+ (void)defaultSetLanguage {
    if (![[NSUserDefaults standardUserDefaults]objectForKey:kBRLanguageKey]) {
        NSArray *languages = [NSLocale preferredLanguages];
        NSString *language = [languages objectAtIndex:0];
        if ([language hasPrefix:@"zh-Hans"]) {//开头匹配
            [[NSUserDefaults standardUserDefaults] setObject:@"zh-Hans" forKey:kBRLanguageKey];
        }else if ([language hasPrefix:@"en"]){
            [[NSUserDefaults standardUserDefaults] setObject:@"en" forKey:kBRLanguageKey];
        }else {
            // 默认支持语言为英语
            [[NSUserDefaults standardUserDefaults] setObject:@"en" forKey:kBRLanguageKey];
        }
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}


#pragma mark - App版本
+ (NSString *)getAppVersion {
    NSString *strCurAppVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
    return strCurAppVersion;
}

+ (NSString *)br_getLanguage {
    return [[NSUserDefaults standardUserDefaults] objectForKey:kBRLanguageKey];
}

+ (NSString *)br_requstLanguage {
    
    NSString *str = [[self class] br_getLanguage];
    
    if ([str containsString:@"zh"]) {
        return @"ZH";
    }
    else if ([str containsString:@"ru"]) {
        return  @"RU";
    }
    else if ([str containsString:@"nl"]) {
        return  @"NL";
    }else if ([str containsString:@"pt-PT"]) {
        return  @"PT";
    }
    
    
    return str.uppercaseString;
}

+ (NSString *)br_timeFormatterInLanguage {
    
    NSString *la = [[self class] br_getLanguage];
    
    if ([la containsString:@"zh"]) {
        return @"yyyy年MM月dd日";
    }
    
    return @"dd MMM yyyy";
}

+ (CGFloat)currStatusBarHeight {
    
    if (@available(iOS 13.0, *)) {
        UIStatusBarManager *statusBarManager = [UIApplication sharedApplication].windows.firstObject.windowScene.statusBarManager;
        return statusBarManager.statusBarFrame.size.height;
    }
    else {
        return [UIApplication sharedApplication].statusBarFrame.size.height;
    }
}

+ (BOOL)isIPhoneX {
    // 根据安全区域判断
    if (@available(iOS 11.0, *)) {
        CGFloat height = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom;
        return (height > 0);
    } else {
        return NO;
    }
}

//正则判断
+ (BOOL)checkEmail:(NSString *)email {
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//正则判断 5 - 15 长度范围
+ (BOOL)checkPhone:(NSString *)phone {
    
    NSString *phoneRegex = @"[0-9]{8,15}";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:phone];
}
//正则判断 是否数字
+ (BOOL)checkIsNumber:(NSString *)str {
    
    if ([str isEqualToString:@""]) {
        return YES;
    }
    NSString *phoneRegex = @"[0-9]";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:str];
}

//正则判断 是否数字和字母
+ (BOOL)checkIsNumberABC:(NSString *)str {
    
    NSString *phoneRegex = @"^[A-Za-z0-9]+$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:str];
}

+ (BOOL)checkIsInviteCode:(NSString *)str {
    
    NSString *phoneRegex = @"^[A-Za-z0-9]{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:str];
}

+ (BOOL)checkChinsesInput:(NSString *)phone {
    
    NSString *phoneRegex = @"^[\u4e00-\u9fa5]{0,}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:phone];
}

+ (NSString *)changCharBig:(NSString *)str {
    if (str.length == 0) {
        return @"";
    }
    NSCharacterSet*cs;
    cs = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz"] invertedSet];
    NSString*filtered = [[str componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
    return filtered;
}
//禁止输入表情
+ (NSString *)disable_emoji:(NSString *)text {
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f\r\n]" options:NSRegularExpressionCaseInsensitive error:nil];
    
    NSString *modifiedString = [regex stringByReplacingMatchesInString:text options:0 range:NSMakeRange(0, [text length]) withTemplate:@"&&&&****"];
    
    return modifiedString;
}
//^[\u4e00-\u9fa5]{0,}$
+ (BOOL)canInputText:(NSString *)string hasEmail:(BOOL)hasEmail {
    if ([string isEqualToString:@""]) {
        return YES;
    }
    if ([string rangeOfCharacterFromSet:[NSCharacterSet jk_emojiCharacterSet]].location != NSNotFound) {
        return NO; // 如果是 Emoji，则不允许输入
    }
    if ([BRTools checkChinsesInput:string]) {
        return NO;
    }
    
    NSString*tem = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]componentsJoinedByString:@""];
    
    if(![string isEqualToString:tem]) {
        
        return NO;
    }
    
    if ([[BRTools disable_emoji:string] isEqualToString:@"&&&&****"] || [[BRTools disable_emoji:string] isEqualToString:@"&&&&****&&&&****"]) {
        
        return NO;
    }
    
    NSArray *specialStringArray = [NSArray array];
    
    //字符串 .,@,
    NSMutableString *specialStringStr = [NSMutableString stringWithString:@"~,￥,#,&,*,<,>,《,》,(,),[,],{,},【,】,^,/,￡,¤,,|,§,¨,「,」,『,』,￠,￢,￣,（,）,——,+,|,$,€,¥,？,/,|,，,。,!,！,-,:,;,£,?,',%,=,\\,\","];
//    NSString *specialStringStr = @"@,~,￥,#,&,*,<,>,《,》,(,),[,],{,},【,】,^,/,￡,¤,,|,§,¨,「,」,『,』,￠,￢,￣,（,）,——,+,|,$,€,¥,？,/,|,，,。,!,！,-,:,;,£,?,',%,=,\\,\",";
    if (!hasEmail) {
//        specialStringStr = @"~,￥,#,&,*,<,>,《,》,(,),[,],{,},【,】,^,/,￡,¤,,|,§,¨,「,」,『,』,￠,￢,￣,（,）,——,+,|,$,€,¥,？,/,|,，,。,!,！,-,:,;,£,?,',%,=,\\,\",";
        [specialStringStr appendString:@"@,.,"];
    }
    specialStringArray = [specialStringStr componentsSeparatedByString:@","];
    //循环遍历字符串
    for (NSInteger i = 0; i < specialStringArray.count; i++) {
        //判断字符串中是否含有特殊符号
        if ([string rangeOfString:specialStringArray[i]].location != NSNotFound) {
            
            return NO;
        }
    }
    
    //逗号需要特殊处理一下
    if ([string rangeOfString:@","].location != NSNotFound) {
        
        return NO;
    }
    
    NSLog(@"%@",string);
    
    return YES;
}
+ (BOOL)canInputText:(NSString *)string {
    
    return [BRTools canInputText:string hasEmail:YES];
}

+ (NSString *)searchString:(NSString *)old new:(NSString *)newStr rang:(NSRange)rang {
    
    if (old.length == 0) {
        return newStr;
    }
    
    NSString *rStr = [old substringWithRange:NSMakeRange(0, old.length - rang.length)];
    
    rStr = [rStr stringByAppendingString:newStr];
//    NSLog(@"return == [%@]",rStr);
    return rStr;
}

+ (NSString *)hiddenNumStr:(NSString *)str {
    
    if ([[self class] checkPhone:str]) {
        
        NSInteger centNum  = str.length / 2 + str.length %2;
        
        return  [str stringByReplacingOccurrencesOfString:[str substringWithRange:NSMakeRange(centNum - 2,4)]withString:@"****"];
        
    }
    
    return str;
}

//正则判断 otp 4位或6位长度范围
+ (BOOL)checkOTPCode:(NSString *)code {
    
    NSString *phoneRegex = @"^([0-9]{4}|[0-9]{6})$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
    return [phoneTest evaluateWithObject:code];
}

//正则判断
/**
 粘贴板获取邀请码正则：
 \[battbox-[\w]+\]

 栗子：
 [battbox-123456]
 */
+ (BOOL)checkInvCode:(NSString *)code {
    
    NSString *codeRegex = @"\\[battbox-\\w+\\]";
    NSPredicate *codeTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", codeRegex];
    return [codeTest evaluateWithObject:code];
}

// 获取设备uuid
+ (NSString *)getDeviceUUIDStr {
    NSString *currentDeviceUUIDStr = [SAMKeychain passwordForService:@"com.Brezzeglobal.BrezzeSaaSPlatform" account:@"uuid"];
    if (!currentDeviceUUIDStr || [currentDeviceUUIDStr isEqualToString:@""]) {

        CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
        NSString *uuidStr = (__bridge NSString *)CFUUIDCreateString(kCFAllocatorDefault ,uuidRef);
        [SAMKeychain setPassword:[NSString stringWithFormat:@"%@", uuidStr] forService:@"com.Brezzeglobal.BrezzeSaaSPlatform"account:@"uuid"];
        return uuidStr;
    }else {
        return currentDeviceUUIDStr;
    }
}

+ (NSString *)getChargingTime:(NSTimeInterval)time {
    
    int h = (int)time / 3600;
    int m = (int)time % 3600 / 60;
    int s = (int)time % 3600 % 60;
    return [NSString stringWithFormat:@"%02d:%02d:%02d",h,m,s];
}

+ (NSString *)getDuringTimeFromTimestamp:(NSString *)timestamp formatter:(NSString *)formatterString
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat: formatterString];
    NSDate *lastDate = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue] / 1000.];
    NSDate *currentDate = [NSDate date];
    double curTime = [currentDate timeIntervalSince1970];
    if (curTime < timestamp.doubleValue / 1000.) {
        return @"00:00:00:00";
    }
    // 当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 需要对比的时间数据
    NSCalendarUnit unit = /*NSCalendarUnitYear | NSCalendarUnitMonth
                           | */NSCalendarUnitDay |  NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:lastDate toDate:currentDate options:0];
    return [NSString stringWithFormat: @"%02ld:%02ld:%02ld:%02ld",dateCom.day, dateCom.hour, dateCom.minute, dateCom.second];
}

+ (NSString *)getDurationTimeInDetail:(NSString *)timestamp formatter:(NSString *)formatterString
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat: formatterString];
    NSDate *lastDate = [NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue] / 1000];
    NSDate *currentDate = [NSDate date];
    double curTime = [currentDate timeIntervalSince1970];
    if (curTime < timestamp.doubleValue / 1000) {
        return @"00Hrs : 00Mins : 00Secs";
    }
    // 当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 需要对比的时间数据
    NSCalendarUnit unit = /*NSCalendarUnitYear | NSCalendarUnitMonth
                           |*/ NSCalendarUnitDay |  NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:lastDate toDate:currentDate options:0];
    if (dateCom.day > 0) {
        return [NSString stringWithFormat: @"%ldDays : %02ldHrs : %02ldMins : %02ldSecs",dateCom.day,dateCom.hour, dateCom.minute, dateCom.second];
    }
    return [NSString stringWithFormat: @"%02ldHrs : %02ldMins : %02ldSecs", dateCom.hour, dateCom.minute, dateCom.second];
}

+ (NSDate *)getNowDateFromatAnDate:(NSDate *)anyDate
{
    //设置源日期时区
    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];//或GMT
    //设置转换后的目标日期时区
    NSTimeZone* destinationTimeZone = [NSTimeZone localTimeZone];
    //得到源日期与世界标准时间的偏移量
    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:anyDate];
    //目标日期与本地时区的偏移量
    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:anyDate];
    //得到时间偏移量的差值
    NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
    //转为现在时间
    NSDate* destinationDateNow = [[NSDate alloc] initWithTimeInterval:interval sinceDate:anyDate];
    return destinationDateNow;
}

+ (NSString *)getFormatTimeFromDurationTime:(NSInteger)durationTime {
    
    CGFloat d = durationTime / (3600. * 24.);
    CGFloat h = durationTime % (3600 * 24) / 3600.;
    CGFloat m = durationTime % 3600 / 60.;
    int s = durationTime % 3600 % 60;
    
    if (floorf(d) > 0) {
//        h = durationTime % 3600 / 3600.;
        return [NSString stringWithFormat:@"%.0fDays : %02.0fHrs : %02.0fMins : %02dSecs",floorf(d),floorf(h),floorf(m),s];
    }
    return [NSString stringWithFormat:@"%02.0fHrs : %02.0fMins : %02dSecs",floorf(h),floorf(m),s];
   
}

+ (NSString *)getTimeFromTimestamp:(NSInteger)time formatter:(NSString *)formatterStr {
    
    if (time >= 10000000000) {
        time = time / 1000;
    }
    //将对象类型的时间转换为NSDate类型
    NSDate * myDate= [NSDate dateWithTimeIntervalSince1970:time];

    //设置时间格式

    NSDateFormatter * formatter=[[NSDateFormatter alloc]init];

    [formatter setDateFormat:formatterStr];
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:[BRLanguageManager share].language];
    //将时间转换为字符串

    NSString *timeStr=[formatter stringFromDate:myDate];

    return timeStr;

}

+ (NSString *)br_timeForMatterDay:(NSInteger)time {
    
    NSString *str = [BRTools getTimeFromTimestamp:time formatter:@"d MMM yyyy"];
    NSArray *days = [str componentsSeparatedByString:@" "];
    if (days.count > 0) {
       
        NSInteger day = [days[0] integerValue];
        
        NSString *dStr = @"th";
        switch (day) {
            case 1:
            case 21:
            case 31:
                dStr = @"st";
                break;
            case 2:
            case 22:
                dStr = @"nd";
                break;
            case 3:
            case 23:
                dStr = @"rd";
                break;
                
            default:
                break;
        }
        NSMutableArray *mut = [NSMutableArray arrayWithArray:days];
        [mut replaceObjectAtIndex:0 withObject:[NSString stringWithFormat:@"%@%@",days[0],dStr]];
        return [mut componentsJoinedByString:@" "];
        
    }
    return str;
}
#pragma mark - 时间到毫秒 --
+ (NSString *)rentingTime:(NSString *)timestamp {
    NSInteger time = [timestamp integerValue];
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a =[date timeIntervalSince1970] * 1000; // *1000 是精确到毫秒，不乘就是精确到秒
    if (a < time) {
        return @"00:00:00.00";
    }
    NSInteger last = a - time;
    NSInteger timeInt = last / 1000;
    CGFloat timeFloat = last / 1000.;
    CGFloat d = timeInt / (3600. * 24.);
//    CGFloat h = timeInt % (3600 * 24) / 3600.; //取值范围24小时内
    CGFloat h = timeInt / 3600.; //直接取多少小时
    CGFloat m = timeInt % 3600 / 60.;
    int s = timeInt % 3600 % 60;
    
    NSString *timeStr = [NSString stringWithFormat:@"%.2f",timeFloat];
    NSArray *times = [timeStr componentsSeparatedByString:@"."];
    timeStr = times[1];
    
    if (floorf(d) > 0) {
//        h = durationTime % 3600 / 3600.;
        return [NSString stringWithFormat:@"%02.0f:%02.0f:%02d.%@",floorf(h),floorf(m),s,timeStr];
    }
    return [NSString stringWithFormat:@"%02.0f:%02.0f:%02d.%@",floorf(h),floorf(m),s,timeStr];
}

// 时间戳转NSDate
+ (NSDate *)getLocateTime:(unsigned int)timeStamp {
    
    double dTimeStamp = (double)timeStamp;
    
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:dTimeStamp];
    
    return confromTimesp;
    
}

//将时间戳转换为NSDate类型
-(NSDate *)getDateTimeFromMilliSeconds:(long long) miliSeconds {
    
    NSTimeInterval tempMilli = miliSeconds;
    
    NSTimeInterval seconds = tempMilli/1000.0;//这里的.0一定要加上，不然除下来的数据会被截断导致时间不一致
    
    NSLog(@"传入的时间戳=%f",seconds);
    
    return [NSDate dateWithTimeIntervalSince1970:seconds];
    
}

//将NSDate类型的时间转换为时间戳,从1970/1/1开始
-(long long)getDateTimeTOMilliSeconds:(NSDate *)datetime {
    
    NSTimeInterval interval = [datetime timeIntervalSince1970];
    
    NSLog(@"转换的时间戳=%f",interval);
    
    long long totalMilliseconds = interval*1000 ;
    
    NSLog(@"totalMilliseconds=%llu",totalMilliseconds);
    
    return totalMilliseconds;
    
}


#pragma mark ---------------------
+ (UIImage *)gradientImageWithColors:(NSArray *)colors rect:(CGRect)rect
{
    return [[self class] gradientImageWithColors:colors rect:rect startPoin:CGPointMake(0.5, 0) endPoint:CGPointMake(1, 1) locations:@[]];
}

+ (UIImage *)gradientHomesShadowImageWithColors:(NSArray *)colors rect:(CGRect)rect
{
    return [[self class] gradientImageWithColors:colors rect:rect startPoin:CGPointMake(0.5, 0) endPoint:CGPointMake(0.5, 0.5) locations:@[@(0), @(1.0f)]];
}

+ (UIImage *)gradientImageWithColors:(NSArray *)colors rect:(CGRect)rect startPoin:(CGPoint)startPoint endPoint:(CGPoint)endPoint locations:(NSArray *)locations {
    if (!colors.count || CGRectEqualToRect(rect, CGRectZero)) {
        return nil;
    }

    CAGradientLayer *gradientLayer = [CAGradientLayer layer];

    gradientLayer.frame = rect;
    gradientLayer.startPoint = startPoint;
    gradientLayer.endPoint = endPoint;
    NSMutableArray *mutColors = [NSMutableArray arrayWithCapacity:colors.count];
    for (UIColor *color in colors) {
        [mutColors addObject:(__bridge id)color.CGColor];
    }
    gradientLayer.colors = [NSArray arrayWithArray:mutColors];
    if (locations.count != 0) {
        gradientLayer.locations = locations;
    }
    UIGraphicsBeginImageContextWithOptions(gradientLayer.frame.size, gradientLayer.opaque, 0);
    [gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outputImage;
}

+ (CAGradientLayer *)gradientLayerWithColors:(NSArray *)colors rect:(CGRect)rect startPoin:(CGPoint)startPoint endPoint:(CGPoint)endPoint locations:(NSArray *)locations {
    if (!colors.count || CGRectEqualToRect(rect, CGRectZero)) {
        return [CAGradientLayer layer];
    }
    
    CAGradientLayer *gl = [CAGradientLayer layer];
    gl.frame = rect;
    gl.startPoint = startPoint;
    gl.endPoint = endPoint;
    NSMutableArray *mutColors = [NSMutableArray arrayWithCapacity:colors.count];
    for (UIColor *color in colors) {
        [mutColors addObject:(__bridge id)color.CGColor];
    }
    gl.colors = [NSArray arrayWithArray:mutColors];

    gl.locations = locations;
    
    return gl;
}

+ (CAGradientLayer *)gradientLayerWithColors:(NSArray *)colors rect:(CGRect)rect {
    
    return [[self class] gradientLayerWithColors:colors rect:rect locations:@[@(0), @(1.0f)]];
}

+ (CAGradientLayer *)gradientLayerWithColors:(NSArray *)colors rect:(CGRect)rect locations:(NSArray *)locations {
    
    return [[self class] gradientLayerWithColors:colors rect:rect startPoin:CGPointMake(0.5, 0) endPoint:CGPointMake(0.5, 1) locations:locations];
}

+ (CAGradientLayer *)gradientLayerWithColors:(NSArray *)colors rect:(CGRect)rect startPoin:(CGPoint)startPoint endPoint:(CGPoint)endPoint {
    return [[self class] gradientLayerWithColors:colors rect:rect startPoin:startPoint endPoint:endPoint locations:@[@(0), @(1.0f)]];
}

+ (NSRange)rangeof:(NSString *)str toStr:(NSString *)text  {
    NSRange rang = NSMakeRange([text rangeOfString:str].location, [text rangeOfString:str].length);
    return rang;
}


/// SF-Pro-Display-HeavyItalic 斜体加粗
/// @param font 字号
/// @param bold 加粗
/// @param italic 斜体
+ (UIFont *)br_displayFontWithSize:(UIFont *)font bold:(BOOL)bold itatic:(BOOL)italic  {

    UIFontDescriptorSymbolicTraits symbolicTraits = 0;
    if (italic) {
        symbolicTraits |= UIFontDescriptorTraitItalic;
    }
    if (bold) {
        symbolicTraits |= UIFontDescriptorTraitBold;
    }
    UIFont *specialFont = [UIFont fontWithDescriptor:[[font fontDescriptor] fontDescriptorWithSymbolicTraits:symbolicTraits] size:font.pointSize];
    return specialFont;
}

#pragma mark - Other --
+ (NSString *)br_getDistance:(NSInteger)distance {
    
    CGFloat mi = distance / 1609.344;
//    if (mi < 100) {
//        return [NSString stringWithFormat:@"%.02f mi",mi];
//    }
//    if (mi < 1000) {
//        return [NSString stringWithFormat:@"%.0f mi",mi];
//    }
    
//    mi = mi / 1000;
    
    return [NSString stringWithFormat:@"%.2f mi",mi];
    
//    if (distance < 1000) {
//        return [NSString stringWithFormat:@"%ld m",distance];
//    }
//    CGFloat distanceF  = distance / 1000.;
//    if (distance < 100) {
//        return [NSString stringWithFormat:@"%.1f km",distanceF ];
//    }
//    return [NSString stringWithFormat:@"%.0f km",distanceF];
}

//处理字符串，使其首字母大写
+ (NSString *)capitalizedString:(NSString *)str {
    NSString *resultStr;
    if(str && str.length>0) {
        resultStr = [str stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[str substringToIndex:1] capitalizedString]];
    }
    return resultStr;
}

+ (NSAttributedString *)br_addAttBottomLine:(NSString *)str {
    NSMutableAttributedString *mString = [[NSMutableAttributedString alloc]initWithString:str];
     
    NSRange range = [str rangeOfString:str];

    [mString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:range];
    
    return mString;
}

+ (void)br_pasteboardString:(NSString *)str {
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = str;
}

+ (NSString *)br_amountVND:(NSNumber *)amount {
    if (amount.floatValue == 0) return @"0.000";
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
    [formatter setGroupingSeparator:@"."]; // 设置千位分隔符
    [formatter setDecimalSeparator:@","]; // 设置小数点分隔符
//    [formatter setPositiveSuffix:@" đ"]; // 设置正数后缀

    NSString *formattedAmount = [formatter stringFromNumber:amount];
    
    return formattedAmount;
}


#pragma mark - 渐变色 --
+ (NSArray *)br_gradientBlueColors1 {
    return @[UIColorMake(0, 185, 255),UIColorMake(60, 144, 255)];
}

+ (NSArray *)br_gradientBlueColors2 {
    return @[UIColorMake(0, 185, 255),UIColorMake(60, 144, 255)];
}

+ (NSArray *)br_gradientBlueColors3 {
    return @[UIColorMake(78, 196, 255),UIColorMake(47, 153, 255)];
}
+ (NSArray *)br_gradientBlueColors4 {
    return @[UIColorMake(0, 185, 255),UIColorMake(185, 235, 255)];
}

+ (NSArray *)br_gradientPaySuccColors1 {
    return @[UIColorMake(0, 144, 255),UIColorMake(0, 185, 255),UIColorMake(255, 255, 255)];
}
+ (NSArray *)br_gradientPayFailColors1 {
    return @[UIColorMake(253, 88, 73),UIColorMake(143, 224, 255),UIColorMake(255, 255, 255)];
}

#pragma mark - 通用参数返回 --
+ (NSString *)strOfType:(NSInteger)type {
    
    NSString *title = Localized(@"help_others");
    switch (type) {
        case 1:{
            title = Localized(@"Help_rent");
            break;
        }
        case 2:{
            title = Localized(@"Help_return");
            break;
        }
        case 3:{
            title = Localized(@"Help_order");
            break;
        }
        case 4:{
            title = Localized(@"Help_powerBank");
            break;
        }
        case 5:{
            title = Localized(@"Help_charges");
            break;
        }
        case 6:{
            title = Localized(@"Help_eWallet");
            break;
        }
        case 7:{
            title = Localized(@"Help_inviteFriends");
            break;
        }
        case 8:{
            title = Localized(@"Help_account");
            break;
        }
        default:
            break;
    }
    
    return title;
}
/// 订单状态：0-初始化 1-租借中 2-待支付 3-已完成 4-已取消 5-调查中 6-已退款 7-已报失
+ (NSString *)strOrderOfType:(NSInteger)type {
    //等待审核
    NSString *title = Localized(@"help_others");
    switch (type) {
        case 1:{
            title = Localized(@"order_renting");
            break;
        }
        case 2:{
            title = Localized(@"order_pendingPayment");
            break;
        }
        case 3:{
            title = Localized(@"order_completed");
            break;
        }
        case 4:{
            title = Localized(@"order_cancelled");
            break;
        }
        case 5:{
            title = Localized(@"order_underInvestigation");
            break;
        }
        case 6:{
            title = Localized(@"order_refund");
            break;
        }
        case 7:{
            title = Localized(@"order_reportedLost");
            break;
        }
        case 8:{
            title = Localized(@"Payment_dueToBuy");
            break;
        }
        
        default:
            break;
    }
    
    return title;
}

+ (NSString *)payWith:(NSInteger)type {
    
    NSString *title = Localized(@"Payment_wallet");
    switch (type) {
        case 0:
        case 1:{
            title = Localized(@"wallet_type_bankcard");
            break;
        }
        case 2:{
            title = Localized(@"Payment_familyCircle");
            break;
        }
        case 3:{
            title = Localized(@"wallet_type_applepay");
            break;
        }
        case 4:{
            title = Localized(@"wallet_type_googlepay");
            break;
        }
        case 5:{
            title = Localized(@"wallet_type_paypal");
            break;
        }
        case 6:{
            title = Localized(@"Payment_weChat");
            break;
        }
        case 7:{
            title = Localized(@"Payment_alipay");
            break;
        }
        default:
            break;
    }
    
    return title;
}
/*
 流水类型：1-租借 2-租金退款 3-会员 4-会员退款 5-押金 6-押金退款 7-罚金 8-罚金退款 9-添加卡 10-添加卡退款  11-购买优惠券 12-优惠券退款  19-充电卡
 */
+ (NSString *)paymentType:(NSInteger)type {
    
    NSString *title = Localized(@"help_others");
    switch (type) {
        case 1:
        case 2:{
            title = Localized(@"pay_rental");
            break;
        }
//        case 2:{
//            title = Localized(@"Payment_refundRental");
//            break;
//        }
//        case 3:{
//            title = Localized(@"Payment_vip");
//            break;
//        }
//        case 4:{
//            title = Localized(@"Payment_refundVip");
//            break;
//        }
        case 5:
        case 6:{
            title = Localized(@"pay_deposit");
            break;
        }
//        case 6:{
//            title = Localized(@"Payment_renfundDeposit");
//            break;
//        }
        case 7:
        case 8:{
            title = Localized(@"pay_powerbank");
            break;
        }
        case 19:
        case 20:{
            title = Localized(@"charge_card");
            break;
        }
        default:
            break;
    }
    
    return title;
}

+ (NSString *)payType:(NSInteger)type {
    //流水类型：1-租借 3-会员 5-押金 7-罚金 11-添加卡 19-充电卡
    NSString *title = Localized(@"pay_rental");
    switch (type) {
        case 1:{
            title = Localized(@"pay_rental");
            break;
        }
        case 3:{
            title = @"VIP";
            break;
        }
        case 5:{
            title = Localized(@"pay_deposit");
            break;
        }
        case 7:{
            title = Localized(@"pay_powerbank");
            break;
        }
        case 19:
        case 20:{
            title = Localized(@"charge_card");
            break;
        }
    }
    
    return title;
}

+ (void)br_resultDo:(NSDictionary *)dataDic text:(NSString *)textKey by:(UIViewController *)vc {
    
    NSInteger result = [dataDic[@"data"][@"result"] integerValue];
    //0:成功 1：有租借中的订单 2：有未支付的订单 3：有调查中的订单4：子账号有未完成的订单 5：子账号有调查中的订单 6：子账号有租借中的订单 7:已开通亲情圈
    NSString *text = [NSString stringWithFormat:@"%@%ld",textKey,result];
    switch (result) {
        case 2:{
            BROrderDetailModel *model = [BROrderDetailModel mj_objectWithKeyValues:dataDic[@"data"][@"order"]];
            if (model.money.floatValue == 0) {
                return;
            }
//            WS(weakSelf);
            BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:Localized(@"public_notice") subTitle:Localized(text) cancelStr:Localized(@"public_notNow") succStr:Localized(@"home_gotoPay") cancelAction:^{
                
            } successAction:^{
                BRPaymentViewController *payVC = [[BRPaymentViewController alloc] init];
                
                payVC.amount = model.money;
                payVC.payType = BRPAY_Rent;
                payVC.dto = model;
                [vc.navigationController pushViewController:payVC animated:YES];
            } showBC:YES];
            
            [vc.view addSubview:alertV];
//            [BRHud showTips:Localized(text)];
            
            
            break;
        }
        case 1:
        case 3:{
            
            
            BRCustiomAlertView *alertV = [[BRCustiomAlertView alloc] initWithTitle:Localized(@"public_notice") subTitle:Localized(text) cancelStr:Localized(@"profile_confirm") succStr:@"" cancelAction:^{
                
            } successAction:^{
                
            } showBC:YES];
            
            [vc.view addSubview:alertV];
            
            break;
        }
        case 4:
        case 5:
        case 6:{
            
            [BRHud showAuto:Localized(text) inView:vc.view];
            
            break;
        }
            
        default:
            break;
    }
}

//+ (NSString *)getMCC{
//
//    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
//
//    CTCarrier *carrier = [info subscriberCellularProvider];
//
//    NSString *mcc = [carrier mobileCountryCode];
////    NSString *mnc = [carrier mobileNetworkCode];
//
////    NSString *imsi = [NSString stringWithFormat:@"%@%@", mcc, mnc];
//
//    return mcc;
//}

/// 使用状态颜色（新接口）：1-使用中 2-已归还 3-已购买(正常流程) 4-已购买(丢失) 5-已购买(超时) 6-其他状态
+ (UIColor *)colorOrderUsingStatus:(NSInteger)usingStatus {
    NSString *colorStr = @"#95A5A6"; // 默认灰色（其他状态）
    switch (usingStatus) {
        case 1: { // 使用中 (renting)
            colorStr = @"#FFD700";
            break;
        }
        case 2: { // 已归还 (returned)
            colorStr = @"#FF6B6B";
            break;
        }
        case 3: { // 已购买（正常流程）(purchased)
            colorStr = @"#4ECDC4";
            break;
        }
        case 4: { // 已购买（丢失）(purchasedLost)
            colorStr = @"#FF6B35";
            break;
        }
        case 5: { // 已购买（超时）(purchasedTimeout)
            colorStr = @"#9B59B6";
            break;
        }
        case 6: { // 其他状态 (otherStatus)
            colorStr = @"#95A5A6";
            break;
        }
        default: {
            colorStr = @"#95A5A6";
            break;
        }
    }
    return UIColorMakeWithHex(colorStr);
}

/// 使用状态文字（新接口）：1-使用中 2-已归还 3-已购买(正常流程) 4-已购买(丢失) 5-已购买(超时) 6-其他状态
+ (NSString *)strOrderUsingStatus:(NSInteger)usingStatus {
    NSString *title = Localized(@"order_otherStatus");
    switch (usingStatus) {
        case 1: { // 使用中 (renting)
            title = Localized(@"order_renting");
            break;
        }
        case 2: { // 已归还 (returned)
            title = Localized(@"order_returned");
            break;
        }
        case 3: { // 已购买（正常流程）(purchased)
            title = Localized(@"order_purchased");
            break;
        }
        case 4: { // 已购买（丢失）(purchasedLost)
            title = Localized(@"order_purchasedLost");
            break;
        }
        case 5: { // 已购买（超时）(purchasedTimeout)
            title = Localized(@"order_purchasedTimeout");
            break;
        }
        case 6: { // 其他状态 (otherStatus)
            title = Localized(@"order_otherStatus");
            break;
        }
        default: {
            title = Localized(@"order_otherStatus");
            break;
        }
    }
    return title;
}

#pragma mark - 位置相关
+ (CLLocationCoordinate2D)br_getGlobalLocation {
    // 从全局管理器获取位置，如果没有设置则返回(0,0)，等待真实定位
    CGFloat lat = USERManager.globalLatitude;
    CGFloat lng = USERManager.globalLongitude;
    
    // 返回真实位置，如果为0则返回(0,0)，不再使用固定位置
    return CLLocationCoordinate2DMake(lat, lng);
}

/// 坐标转换：BD09（百度坐标系）转 GCJ02（火星坐标系）- 用于显示到Google Maps（与H5保持一致）
/// 算法参考：https://github.com/wandergis/coordtransform
/// 性能优化：预计算常量，减少重复计算
+ (CLLocationCoordinate2D)br_bd09ToGcj02:(CGFloat)bd09Lat lng:(CGFloat)bd09Lng {
    // 预计算常量
    static const double PI_3000_180 = M_PI * 3000.0 / 180.0;
    static const double OFFSET_LNG = 0.0065;
    static const double OFFSET_LAT = 0.006;
    static const double CORRECTION_SIN = 0.00002;
    static const double CORRECTION_COS = 0.000003;
    
    double x = bd09Lng - OFFSET_LNG;
    double y = bd09Lat - OFFSET_LAT;
    double x2 = x * x;
    double y2 = y * y;
    double z = sqrt(x2 + y2) - CORRECTION_SIN * sin(y * PI_3000_180);
    double theta = atan2(y, x) - CORRECTION_COS * cos(x * PI_3000_180);
    double cosTheta = cos(theta);
    double sinTheta = sin(theta);
    double gcj02Lng = z * cosTheta;
    double gcj02Lat = z * sinTheta;
    return CLLocationCoordinate2DMake(gcj02Lat, gcj02Lng);
}

/// 坐标转换：GCJ02（火星坐标系）转 BD09（百度坐标系）- 用于请求接口（与H5保持一致）
/// 性能优化：预计算常量，减少重复计算
+ (CLLocationCoordinate2D)br_gcj02ToBd09:(CGFloat)gcj02Lat lng:(CGFloat)gcj02Lng {
    // 预计算常量
    static const double PI_3000_180 = M_PI * 3000.0 / 180.0;
    static const double OFFSET_LNG = 0.0065;
    static const double OFFSET_LAT = 0.006;
    static const double CORRECTION_SIN = 0.00002;
    static const double CORRECTION_COS = 0.000003;
    
    double lng2 = gcj02Lng * gcj02Lng;
    double lat2 = gcj02Lat * gcj02Lat;
    double z = sqrt(lng2 + lat2) + CORRECTION_SIN * sin(gcj02Lat * PI_3000_180);
    double theta = atan2(gcj02Lat, gcj02Lng) + CORRECTION_COS * cos(gcj02Lng * PI_3000_180);
    double cosTheta = cos(theta);
    double sinTheta = sin(theta);
    double bd09Lng = z * cosTheta + OFFSET_LNG;
    double bd09Lat = z * sinTheta + OFFSET_LAT;
    return CLLocationCoordinate2DMake(bd09Lat, bd09Lng);
}

#pragma mark - 协议URL生成
/// 根据类型和当前语言生成协议URL
/// @param type 0-用户协议 1-隐私政策
+ (NSString *)br_agreementURLWithType:(NSInteger)type {
    // 获取当前语言
    NSString *currentLang = [BRLanguageManager share].language;
    NSString *langParam = @"";
    
    // 语言映射：vi -> vi, zh-Hans -> cn, en -> en
    if ([currentLang isEqualToString:@"vi"]) {
        langParam = @"vi";
    } else if ([currentLang isEqualToString:@"zh-Hans"] || [currentLang hasPrefix:@"zh"]) {
        langParam = @"cn";
    } else if ([currentLang isEqualToString:@"en"]) {
        langParam = @"en";
    } else {
        // 默认使用当前语言
        langParam = currentLang;
    }
    
    // 根据类型生成URL
    NSString *baseURL = @"";
    if (type == 0) {
        // 用户协议
        baseURL = @"https://s.youdianstar.com/sw/app/agreement/user.html";
    } else {
        // 隐私政策
        baseURL = @"https://s.youdianstar.com/sw/app/agreement/privacy.html";
    }
    
    return [NSString stringWithFormat:@"%@?lang=%@", baseURL, langParam];
}

#pragma mark - 金额格式化
/// 格式化越南盾金额（支持小数，每3位加一个点）
/// 规则：
/// - 整数部分：从右往左每3位加一个点（.）
/// - 小数部分：如果有有效数字就显示，去掉末尾的0；如果没有有效数字就不显示小数点
/// 示例：
/// - 3000 -> "3.000"
/// - 3000.00 -> "3.000"
/// - 3000.50 -> "3.000.5"
/// - 300000 -> "300.000"
+ (NSString *)br_formatVietnameseDong:(CGFloat)amount {
    if (amount == 0) {
        return @"0";
    }
    
    // 分离整数部分和小数部分
    NSInteger integerPart = (NSInteger)floor(amount);
    CGFloat decimalPart = amount - integerPart;
    
    // 格式化整数部分：从右往左每3位加一个点
    NSMutableString *integerStr = [NSMutableString stringWithFormat:@"%ld", (long)labs(integerPart)];
    if (integerPart < 0) {
        [integerStr insertString:@"-" atIndex:0];
    }
    NSInteger length = integerStr.length;
    NSInteger startIndex = integerPart < 0 ? 1 : 0; // 如果有负号，从索引1开始
    
    // 从右往左每3位插入一个点
    for (NSInteger i = length - 3; i > startIndex; i -= 3) {
        [integerStr insertString:@"." atIndex:i];
    }
    
    // 处理小数部分
    // 使用精度比较，避免浮点数精度问题
    if (fabs(decimalPart) > 0.0001) {
        // 将小数部分转换为字符串，保留足够的小数位以便去掉末尾的0
        NSString *decimalStr = [NSString stringWithFormat:@"%.10f", decimalPart];
        // 去掉前导的"0."
        if ([decimalStr hasPrefix:@"0."]) {
            decimalStr = [decimalStr substringFromIndex:2];
        }
        // 去掉末尾的0
        NSCharacterSet *zeroSet = [NSCharacterSet characterSetWithCharactersInString:@"0"];
        decimalStr = [decimalStr stringByTrimmingCharactersInSet:zeroSet];
        // 去掉末尾的点（如果只剩下点）
        if ([decimalStr hasSuffix:@"."]) {
            decimalStr = [decimalStr substringToIndex:decimalStr.length - 1];
        }
        
        // 如果还有有效小数部分，添加到结果中
        if (decimalStr.length > 0 && ![decimalStr isEqualToString:@"0"] && ![decimalStr isEqualToString:@"0."]) {
            return [NSString stringWithFormat:@"%@.%@", integerStr, decimalStr];
        }
    }
    
    return integerStr;
}

@end


@implementation BRStringTools

+ (NSAttributedString *)br_attLineSpace:(CGFloat)space text:(NSString *)text range:(NSRange)range {
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];

    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = space;

    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];

   
    
    return attributedString;
}

+ (NSAttributedString *)br_att:(NSString *)text rang:(NSRange)rang textC:(UIColor *)textColor {
    
    return [BRStringTools br_att:text rang:rang textC:textColor font:nil];
}

+ (NSAttributedString *)br_att:(NSString *)text rang:(NSRange)rang font:(UIFont  *)font {
    
    return [BRStringTools br_att:text rang:rang textC:nil font:font];
}

+ (NSAttributedString *)br_att:(NSString *)text rang:(NSRange)rang textC:(UIColor * _Nullable)textColor font:(UIFont  * _Nullable)font {
    
    // 创建一个可变的富文本实例
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:text];
    // 设置 色
    if (textColor) [attributedString addAttribute:NSForegroundColorAttributeName value:textColor range:rang];
    // 设置 字体
    if (font) [attributedString addAttribute:NSFontAttributeName value:font range:rang];
    
    return attributedString;
}



+ (NSString *)br_couponsTypeStr:(NSInteger)type {
    
    //抵扣类型：1-金额 2-时间 3-折扣 抵扣类型:1-免费时长 2-优惠金额 3-金额折扣"
    if (type == 2) return Localized(@"coupon_freeRental");
    if (type == 1) return Localized(@"coupon_freeUsage");
    return Localized(@"coupon_rentalDiscount");
}

+ (NSString *)br_couponsTypeContent:(BRCouponModel *)dto {
    
    NSString *text = @"";
    NSInteger couponType = dto.deductionType;
    if (couponType == 1) {
        text = [BRPayManager br_amount:dto.amount];
    }else if (couponType == 2) {
        text = [BRStringTools br_couponTimeJson:dto.time];
    }else if (couponType == 3) {
        text = [NSString stringWithFormat:@"%ld%% %@",dto.discount,Localized(@"coupon_off")];;
    }
    return text;
}

+ (NSString *)br_couponsTypeContentV2:(BRCouponDeductionModel *)dto {
    
    NSString *text = @"";
    NSInteger couponType = dto.type;
    if (couponType == 1) {
        NSString *timeStr = dto.type1FreeDurationUnit == 1 ? Localized(@"coupon_min") : Localized(@"coupon_hour");
        text = [NSString stringWithFormat:@"%ld %@",dto.type1FreeDurationVal,timeStr];
    }else if (couponType == 2) {
        text =  [BRPayManager br_amount:dto.type2DiscountAmount];
    }else if (couponType == 3) {
        NSInteger discount = dto.type3DiscountAmount;
        text = [NSString stringWithFormat:@"%ld%% %@",discount,Localized(@"coupon_off")];;
    }
    return text;
}

+ (NSString *)br_couponTypeTime:(BRCouponModel *)dto {
    
    NSInteger couponType = dto.deductionType;
    NSString *title1 = [BRStringTools br_couponsTypeStr:couponType];
    NSString *text1 = [BRStringTools br_couponsTypeContentV2:dto.deduction];
    
    return [NSString stringWithFormat:@"%@ %@",title1,text1];
}


+ (NSString *)br_couponTimeJson:(NSString *)timeJson {
//    NSString *timeJson = dto.time;
    NSDictionary *dic = timeJson.mj_JSONObject;
    if (BR_DictIsEmpty(dic)) {
        return @"--";
    }
    BRCouponTimeModel *timeM = [BRCouponTimeModel mj_objectWithKeyValues:dic];
    NSString *timeStr = @"";
    if (timeM.day > 0) {
        timeStr = [NSString stringWithFormat:@"%ld %@",timeM.day,Localized(@"coupon_day")];
    }
    if (timeM.hour > 0) {
        NSString *jge = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ ",timeStr] : @"";
        timeStr = [NSString stringWithFormat:@"%@%ld %@",jge,timeM.hour,Localized(@"coupon_hour")];
    }
    if (timeM.minute > 0) {
        NSString *jge = timeStr.length > 0 ? [NSString stringWithFormat:@"%@ ",timeStr] : @"";
        timeStr = [NSString stringWithFormat:@"%@%ld %@",jge,timeM.minute,Localized(@"coupon_min")];
    }
    return timeStr;
}


+ (NSString *)br_chargeCardOfTime:(NSInteger )time {
    
    if (time == 0) {
        return @"--";
    }
    if (time / 3600 >= 1) {
        NSInteger h = time / 3600;
//        NSString *hTime = h > 1 ? Localized(@"time_hours") : Localized(@"time_hour");
        NSString *hTime = Localized(@"coupon_hour");
        return [NSString stringWithFormat:@"%@ %ld %@",Localized(@"coupon_freeUsage"),h,hTime];
        
    }
    NSInteger m = time / 60;
//    NSString *mTime = m > 1 ? Localized(@"time_mins") : Localized(@"time_min");
    NSString *mTime = Localized(@"coupon_min");
    return [NSString stringWithFormat:@"%@ %ld %@",Localized(@"coupon_freeUsage"),m,mTime];
    
}

//+ (NSString *)br_ruleOfModel:(BRRuleModel *)dto {
//    //The first [XXX] minutes/hour/day is free, [XXX] ₫/[XXX] minutes/hour/day thereafter. Daily Cap is [XXX] ₫ . Penalty will be triggered after [xxx] minutes/hours/days.
//    //First %ld mins %@%.2f, %@%.2f/ %ld %@ thereafter. Daily cap %@%.2f. Penalty will be triggered after %ld hours.
//    //The first %ld %@ is free, %@%@/%ld %@ thereafter. Daily Cap is %@%@. Penalty will be triggered after %ld %@
//    
//    NSString *fistT = [BRStringTools br_ruleTimeTyp:dto.freeDurationControlType];
//    NSString *afterT = [BRStringTools br_ruleTimeTyp:dto.controlType];
//    NSString *maxT = [BRStringTools br_ruleTimeTyp:dto.maxDurationControlType];
//    NSString *priceSymbol = USERManager.priceSymbol;
//    return [NSString stringWithFormat:Localized(@"rent_rule"),dto.freeDuration,fistT,dto.upfrontAmount,priceSymbol,dto.upfrontDuration,afterT,dto.dayAmount,priceSymbol,dto.maxRentDuration,maxT];
//}

+ (NSString *)br_ruleTimeTyp:(NSInteger)type {
    //：1-分 2-小时
    if (type == 1) return Localized(@"rule_min");
    
    return Localized(@"rule_hour");;
}


/// 订单状态：0-初始化 1-租借中 2-待支付 3-已完成 4-已取消 5-调查中 6-已退款 7-已报失 8-已购买
+ (UIColor *)colorOrderOfType:(NSInteger)type {
    NSString *colorStr = @"#00B9FF";
    switch (type) {
        case 1:{
            colorStr = @"#00B9FF";
            break;
        }
        case 2:{
            colorStr = @"#FFC855";
            break;
        }
        case 3:{
            colorStr = @"#4CE48A";
            break;
        }
        case 4:{
            colorStr = @"#99999B";
            break;
        }
        case 5:{
            colorStr = @"#FFC855";
            break;
        }
        case 6:{
            colorStr = @"#FF605A";
            break;
        }
        case 7:{
            colorStr = @"#FF605A";
            break;
        }
        case 8:{
            colorStr = @"#4CE48A";
            break;
        }
        default:
            break;
    }
    
    return UIColorMakeWithHex(colorStr);
    
}
/// 订单状态：0-初始化 1-租借中 2-待支付 3-已完成 4-已取消 5-调查中 6-已退款 7-已报失
+ (NSString *)strOrderOfType:(NSInteger)type {
    //等待审核
    NSString *title = Localized(@"help_others");
    switch (type) {
        case 1:{
            title = Localized(@"order_renting");
            break;
        }
        case 2:{
            title = Localized(@"order_pendingPayment");
            break;
        }
        case 3:{
            title = Localized(@"order_completed");
            break;
        }
        case 4:{
            title = Localized(@"order_cancelled");
            break;
        }
        case 5:{
            title = Localized(@"order_underInvestigation");
            break;
        }
        case 6:{
            title = Localized(@"wallet_refund");
            break;
        }
        case 7:{
            title = Localized(@"order_reportedLost");
            break;
        }
        case 8:{
            title = Localized(@"order_completed");
            break;
        }
        
        default:
            break;
    }
    
    return title;
}

+ (NSString *)br_transactionRecord:(NSInteger)type {
    
    //    类型：1-订单分成 2-调整 3-退款
    if (type == 3) return Localized(@"coupon_merchantCoupon");
    return Localized(@"order_completed");
}

+ (UIColor *)br_stationStateColor:(NSInteger)state {
    
    if (state == 0) {
        return UIColorMakeWithHex(@"#FF605A");
    }
    if (state == 1) {
        return UIColorMakeWithHex(@"#4CE48A");
    }
    if (state == 3) {
        return UIColorMakeWithHex(@"#4CE48A");
    }
    return UIColorMakeWithHex(@"#88888B");
}
+ (NSString *)br_stationStateStr:(NSInteger)state {
    
    if (state == 0) {
        return Localized(@"shop_offline");
    }
    if (state == 1) {
        return Localized(@"shop_online");
    }
    if (state == 3) {
        return Localized(@"shop_available");
    }
    return Localized(@"shop_locked");
}

/// 状态：0-申请中 1-已结算 2-驳回申请
+ (NSString *)strWithdrawalRecordOfType:(NSInteger)type {
    
    if (type == 1) return Localized(@"shop_completed");
    if (type == 2) return Localized(@"shop_rejected");
    return Localized(@"shop_pendingReview");
}
+ (UIColor *)colorWithdrawalRecordOfType:(NSInteger)type {
    
    if (type == 1) return UIColorMakeWithHex(@"#4CE48A");
    if (type == 2) return UIColorMakeWithHex(@"#FF605A");
    return UIColorMakeWithHex(@"#FFC855");
}

+ (NSString *)br_stringEmpty:(NSString *)str {
    
    if (str.length != 0) return str;
    
    return @"--";
}

+ (CGFloat)br_textHeightOf:(NSString *)text font:(UIFont *)font conSize:(CGSize)constraintSize {
    
    CGRect textRect =  [text boundingRectWithSize:constraintSize
                                         options:NSStringDrawingUsesLineFragmentOrigin
                                      attributes:@{NSFontAttributeName:font}
                                         context:nil];
    
    CGFloat textHeight = ceil(textRect.size.height);
    return textHeight;
    
}


@end

@implementation BRImgTools

+ (UIImage *)br_qrLink:(NSString *)link {
    
    
    NSString *urlString = link; // 替换为你要生成二维码的链接

    // 创建二维码滤镜
    CIFilter *qrCodeFilter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    [qrCodeFilter setValue:[NSData dataWithBytes:[urlString UTF8String] length:[urlString length]] forKey:@"inputMessage"];

    // 获取生成的二维码图像
    CIImage *qrCodeImage = qrCodeFilter.outputImage;
    
    return [BRImgTools br_fullImage:qrCodeImage width:kScreenWidth - 58];
}

+ (UIImage *)br_fullImage:(CIImage *)Image width:(CGFloat)w {
    
    CGRect extent = CGRectIntegral(Image.extent);
    
    CGFloat scale = MIN(w / CGRectGetWidth(extent), w / CGRectGetHeight(extent));
    
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    
    CGColorSpaceRef  colorSpaceRef = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, colorSpaceRef, kCGImageAlphaNone);
    
    CIContext *context = [CIContext contextWithOptions:nil];
    
    CGImageRef bitmapImage = [context createCGImage:Image fromRect:extent];
    
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    
    CGContextScaleCTM(bitmapRef, scale, scale);
    
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    
    CGImageRef scaleImg = CGBitmapContextCreateImage(bitmapRef);
    
    CGContextRelease(bitmapRef);
    
    CGImageRelease(bitmapImage);
    
    CGColorSpaceRelease(colorSpaceRef);
    
    return [UIImage imageWithCGImage:scaleImg];
    
}
@end

@implementation BRTimeTools

+ (NSArray *)br_timeDateHoursMin {
    NSMutableArray *all = [NSMutableArray array];
    
    NSMutableArray *hoursArr = [NSMutableArray array];
    for (int h = 0; h < 24 ; h++) {
        
        NSString *hours = [NSString stringWithFormat:@"%02d",h];
        [hoursArr addObject:hours];
    }
    NSMutableArray *minArr = [NSMutableArray array];
    for (int m = 0; m < 60 ; m++) {
        
        NSString *min = [NSString stringWithFormat:@"%02d",m];
        [minArr addObject:min];
    }
    [all addObject:hoursArr];
    [all addObject:minArr];
    
    
    return all;
}

@end
